package com.qxzn.app.page.robot;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.RobotDetails;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.R;
import com.qxzn.app.page.R2;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddRobotQRActivity extends BaseActivity implements QRCodeView.Delegate {
    @BindView(R2.id.zxv_add)
    ZXingView zxvAdd;

    private CountDownTimer timer = new CountDownTimer(30000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            startActivity(new Intent(AddRobotQRActivity.this, AddRobotActivity6.class));
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.activity_add_robot_qr;
    }

    @Override
    protected void initView() {
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.iv_right) {
            Matisse.from(this)
                    .choose(MimeType.ofImage())
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, Constant.authority))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideImageLoader.Glide4Engine())
                    .forResult(1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        zxvAdd.startSpotAndShowRect(); // 显示扫描框，并开始识别
        if (resultCode == RESULT_OK && requestCode == 1) {
            List<String> strings = Matisse.obtainPathResult(data);
            if (strings != null && strings.size() > 0) {
                zxvAdd.decodeQRCode(strings.get(0));
            }
        }
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("扫码添加机器人");
//        iv_right.setVisibility(View.VISIBLE);
        iv_right.setImageResource(R.mipmap.icon_get_pic_local);
        iv_right.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        zxvAdd.setDelegate(this);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        AppUtil.showLog("扫描结果：" + result);
//        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//        if (vibrator != null)
//            vibrator.vibrate(200);
        getRobotInfo(result);
    }

    private void getRobotInfo(String deviceId) {
        JSONObject params = new JSONObject();
        params.put("device_id", deviceId);
        HttpRequest.getService().getRobotDetails(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean<RobotDetails>>() {
            @Override
            public void onResponse(Call<BaseBean<RobotDetails>> call, Response<BaseBean<RobotDetails>> response) {
                BaseBean<RobotDetails> robotDetailsBaseBean = response.body();
                if (robotDetailsBaseBean.getCode() == 200) {
                    RobotDetails robotDetails = robotDetailsBaseBean.getData();

                    HttpRequest.getService().getRobotRoles(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
                        @Override
                        public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                            if (response.body().getCode() == 200) {
                                startActivity(new Intent(AddRobotQRActivity.this, AddRobotActivity1.class)
                                    .putExtra(Constant.PutExtraKey.DEVICE_ID, robotDetails.device_id)
                                    .putExtra(AddRobotActivity1.ADMIN_NAME, robotDetails.niname)
                                    .putExtra(AddRobotActivity1.ROBOT_NAME, robotDetails.name));
                            } else {
                                autoBinding(robotDetails.device_id);
                            }
                        }

                        @Override
                        public void onFailure(Call<BaseBean> call, Throwable t) {
                            ToastUtil.showTextToast(getApplicationContext(), getString(R.string.network_error));
                            zxvAdd.startSpot();
                        }
                    });

                } else {
                    zxvAdd.startSpot();
                }
            }

            private void autoBinding(String device_id) {
                showProgress();
                JSONObject params = new JSONObject();
                params.put("device_id", device_id);
                params.put("username", SharePreferenceUtil.getUserName(getApplicationContext()));
                HttpRequest.getService().bingingByAsk(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
                    @Override
                    public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                        hideProgress();
                        BaseBean body = response.body();
                        if (body.getCode() == 200)
                            startActivity(new Intent(AddRobotQRActivity.this, AddRobotActivity4.class));
                        else {
                            ToastUtil.showTextToast(getApplicationContext(), body.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseBean> call, Throwable t) {
                        hideProgress();
                        ToastUtil.showTextToast(getApplicationContext(), getString(R.string.network_error));
                    }
                });
            }

            @Override
            public void onFailure(Call<BaseBean<RobotDetails>> call, Throwable t) {
                ToastUtil.showTextToast(getApplicationContext(), getString(R.string.network_error));
                zxvAdd.startSpot();
            }
        });
    }


    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
//        String tipText = zxvAdd.getScanBoxView().getTipText();
//        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
//        if (isDark) {
//            if (!tipText.contains(ambientBrightnessTip)) {
//                zxvAdd.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
//            }
//        } else {
//            if (tipText.contains(ambientBrightnessTip)) {
//                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
//                zxvAdd.getScanBoxView().setTipText(tipText);
//            }
//        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        AppUtil.showLog("打开相机出错");
    }

    @Override
    protected void onResume() {
        super.onResume();
        timer.start();
        zxvAdd.startSpot();
    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        zxvAdd.stopSpot();
    }

    @Override
    protected void onStart() {
        super.onStart();
        zxvAdd.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        zxvAdd.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        zxvAdd.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        zxvAdd.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zxvAdd.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

}
